package artid.com.arttogoa;

import java.io.IOException;
import org.apache.commons.lang3.StringUtils;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.MD5;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称：PersonalActivity 类描述：个人信息 创建人：耿卫斌 创建时间：2016年5月16日
 * 下午2:29:38
 * 
 */
public class PersonalActivity extends BaseActivity implements

OnClickListener {
	private RelativeLayout mCertification, mFans, mMessage, mAddress, mCoupons,
			mSetting, mFeedback, shareWeiZhanRL, my_sell_RL,
			transactionManagementRL, artPush_Rl, authenticationOperation;
	private LinearLayout mPersonalDetail, priceLL;
	private Intent mIntent;
	private TextView native_place, good_at, university, classes_tv;
	private ImageView photoImg, IsAuth, unreadMessage_icon;
	Boolean isSetPic = false;
	private TextView follownumber, headCompile, personal_price_tv;
	private ImageLoader mImageLoader;
	private String PhotoPath;// 剪裁之后图片路径
	private Bitmap clipBitmap;// 剪裁之后的图片
	private String Bitmap64;// 剪裁之后的图片流
	private ImageView settingBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personal);
		setContent(this, getIntent());
		setBack();
		ArtWorkApp.getInstance().addActivity(this);
		mContext = this;
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.PersonalActivity.receiver");
		registerReceiver(broadcastReceiver, filter);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mCertification = (RelativeLayout) findViewById(R.id.certification_layout);
		mFans = (RelativeLayout) findViewById(R.id.fans_layout);
		mMessage = (RelativeLayout) findViewById(R.id.message_layout);
		mAddress = (RelativeLayout) findViewById(R.id.address_layout);
		authenticationOperation = (RelativeLayout) findViewById(R.id.personal_authentication_operation);
		// mCoupons = (RelativeLayout) findViewById(R.id.coupons_layout);
		mSetting = (RelativeLayout) findViewById(R.id.settings_layout);
		mFeedback = (RelativeLayout) findViewById(R.id.feedback_layout);
		shareWeiZhanRL = (RelativeLayout) findViewById(R.id.personal_shareweizhan);
		my_sell_RL = (RelativeLayout) findViewById(R.id.my_sell_layout);
		artPush_Rl = (RelativeLayout) findViewById(R.id.my_artPush_layout);
		transactionManagementRL = (RelativeLayout) findViewById(R.id.my_transactionManagement_layout);
		mPersonalDetail = (LinearLayout) findViewById(R.id.personal_detail_layout);
		priceLL = (LinearLayout) findViewById(R.id.personal_priceLL);
		personal_price_tv = (TextView) findViewById(R.id.personal_price);
		photoImg = (ImageView) findViewById(R.id.personal_photo);
		photoImg.setOnClickListener(this);
		authenticationOperation.setOnClickListener(this);
		mTittle = (TextView) findViewById(R.id.title_text);
		IsAuth = (ImageView) findViewById(R.id.Personal_IsAuth);
		settingBtn = (ImageView) findViewById(R.id.release_icon);
		settingBtn.setVisibility(View.VISIBLE);
		settingBtn.setImageResource(R.drawable.zjm_btn_shezhi_nor);
		settingBtn.setOnClickListener(this);
		mTittle.setText(AppUtil.getUser().getRealname());
		native_place = (TextView) findViewById(R.id.native_place);
		good_at = (TextView) findViewById(R.id.good_at_field);
		classes_tv = (TextView) findViewById(R.id.personal_classestv);
		university = (TextView) findViewById(R.id.university);
		follownumber = (TextView) findViewById(R.id.Personal_follownumber);
		headCompile = (TextView) findViewById(R.id.Personal_headcompile);
		unreadMessage_icon = (ImageView) findViewById(R.id.Personal_unreadMessage);
		mCertification.setOnClickListener(this);
		mFans.setOnClickListener(this);
		mMessage.setOnClickListener(this);
		mAddress.setOnClickListener(this);
		// mCoupons.setOnClickListener(this);
		mSetting.setOnClickListener(this);
		mFeedback.setOnClickListener(this);
		mPersonalDetail.setOnClickListener(this);
		shareWeiZhanRL.setOnClickListener(this);
		my_sell_RL.setOnClickListener(this);
		transactionManagementRL.setOnClickListener(this);
		priceLL.setOnClickListener(this);
		artPush_Rl.setOnClickListener(this);
		getPersonalMessage();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 刷新是否有信息
		if ("1".equals(MainActivity.isSystemPush)
				|| MainActivity.hxUnreadMessage() != 0
				|| "true".equals(MySharedPreferences.getMySharedPreferences(
						mContext).getValue(
						"isReplyPush" + AppUtil.getUser().getUid(), "false"))) {
			unreadMessage_icon.setVisibility(View.VISIBLE);
		} else {
			unreadMessage_icon.setVisibility(View.GONE);
		}
		if (MainActivity.isRefreshPersonal == true) {
			// 判断是否需要更新个人信息
			getPersonalMessage();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.personal_priceLL:
			// 我的钱包
			mIntent = new Intent(mContext, MyWallet_Activity.class);
			startActivity(mIntent);
			break;
		case R.id.certification_layout:// 我的认证
			if ("0".equals(AppUtil.getUser().getIs_auth())) {
				Intent in = new Intent(PersonalActivity.this,
						RealNameAuthenticationActivity.class);
				startActivity(in);
			} else {
				mIntent = new Intent(PersonalActivity.this,
						RealNameAuthenticationTwoActivity.class);
				startActivity(mIntent);
			}
			break;
		case R.id.my_sell_layout:
			// 我出售的
			mIntent = new Intent(mContext, MySell_Activity.class);
			startActivity(mIntent);
			break;
		case R.id.my_transactionManagement_layout:
			// 交易管理
			mIntent = new Intent(mContext, TransactionManagement_Activity.class);
			startActivity(mIntent);
			break;
		case R.id.fans_layout:// 我的粉丝
			mIntent = new Intent(PersonalActivity.this, MyFansActivity.class);
			startActivity(mIntent);
			break;
		case R.id.message_layout:// 消息管理
			mIntent = new Intent(PersonalActivity.this,

			MessageActivity.class);
			startActivity(mIntent);
			break;
		case R.id.address_layout:// 地址管理
			mIntent = new Intent(PersonalActivity.this,
					AddressManagement_Activity.class);
			mIntent.putExtra("isAddressManagementInetnt", true);
			startActivity(mIntent);
			break;
		// case R.id.coupons_layout:// 我的优惠券
		// mIntent=new Intent(PersonalActivity.this,CouponsActivity.class);
		// startActivity(mIntent);
		// break;
		case R.id.release_icon:// 设置
			mIntent = new Intent(PersonalActivity.this,

			SettingActivity.class);
			startActivity(mIntent);
			break;
		case R.id.personal_authentication_operation:// 认证操作
			mIntent = new Intent(PersonalActivity.this,
					BaseWebView_Activity.class);
			mIntent.putExtra("webURL", Cache.webUrl
					+ "h5/renzheng/renzheng.html");
			mIntent.putExtra("titleName", "认证操作流程");
			startActivity(mIntent);
			break;
		case R.id.feedback_layout:// 问题反馈
			/*
			 * 暂时先不跳 mIntent = new
			 * Intent(PersonalActivity.this,FeedBackActivity.class);
			 * startActivity(mIntent);
			 */
			AlertUtils.MakePhoneDialog(mContext,"拨打客服电话", "010-64688820", this.getWindowManager().getDefaultDisplay().getWidth());
			break;
		case R.id.personal_detail_layout:// 个人信息
			mIntent = new Intent(PersonalActivity.this,
					PersonalMessageActivity.class);
			startActivity(mIntent);
			break;
		case R.id.personal_photo:// 头像
			showPopupWindow();
			break;
		case R.id.personal_shareweizhan:
			// 分享个人微站
			AppUtil.showShare(mContext, AppUtil.getUser().getRealname()
					+ "的个人微站", AppUtil.getUser().getMemo(), AppUtil.getUser()
					.getAvatarurl(), Cache.shardPersonWeiZhan
					+ AppUtil.getUser().getUid());
			break;
		case R.id.my_artPush_layout:
			// 艺推
			mIntent = new Intent(PersonalActivity.this,
					MyArtPush_Activity.class);
			startActivity(mIntent);
			break;
		default:
			break;
		}
	}

	/**
	 * 得到个人信息
	 */
	private void getPersonalMessage() {
		String na = AppUtil.getUser().getPath();
		String name = MD5.getMD5(na) + na.substring(na.lastIndexOf("."));
		String path = Environment.getExternalStorageDirectory() + "/YJB/"
				+ name;
		String SharedPath = MySharedPreferences
				.getMySharedPreferences(mContext).getValue("HeadURL", "");
		// 判断本地保存的头像是否与服务器地址相同
		if (SharedPath.equals(path)) {
			Bitmap smallBitmap = BitmapUtil
					.getSmallFilletBitmap(path, 500, 500);
			if (smallBitmap != null) {
				photoImg.setImageBitmap(smallBitmap);
			} else {
				downloadAndSaveHeadImage();
			}
		} else {
			downloadAndSaveHeadImage();
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getRealname())) {
			mTittle.setText(AppUtil.getUser().getRealname());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getAvatarurl())) {
			headCompile.setVisibility(View.GONE);
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getNative_place())) {
			native_place.setText(AppUtil.getUser().getNative_place());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getGood_at())) {
			good_at.setText(AppUtil.getUser().getGood_at());
		}
		// 重新部署服务器之后删除本地获取分类
		if (!StringUtils.isEmpty(MySharedPreferences.getMySharedPreferences(
				mContext).getValue("Classes" + AppUtil.getUser().getUid(), ""))) {
			classes_tv.setText(MySharedPreferences.getMySharedPreferences(
					mContext).getValue("Classes" + AppUtil.getUser().getUid(),
					""));
		} else {
			if (!StringUtils.isEmpty(AppUtil.getUser().getAname())) {
				classes_tv.setText(AppUtil.getUser().getAname());
			}
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getUniversity())) {
			university.setText(AppUtil.getUser().getUniversity());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getFollownumber())) {
			follownumber.setText(AppUtil.getUser().getFollownumber());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getIs_auth())
				&& "1".equals(AppUtil.getUser().getIs_auth())) {
			IsAuth.setVisibility(View.VISIBLE);
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getAvailable_predeposit())) {
			personal_price_tv.setText("￥"
					+ AppUtil.getUser().getAvailable_predeposit());
		}

	}

	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(
				mContext,
				Integer.parseInt(NetUtils.getDisplayMetrics(
						PersonalActivity.this).get(NetUtils.DM_WIDTH)),
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						switch (v.getId()) {
						case R.id.tv_phone:
							//检查权限
							if (ContextCompat.checkSelfPermission(PersonalActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
								displayFrameworkBugMessageAndExit();
								return;
							}
							// 照相机
							CameraUtils.openCameraImage(PersonalActivity.this);
							AlertUtils.dismiss();
							break;
						case R.id.tv_choice:
							// 从相册获取
							CameraUtils.openLocalImage(PersonalActivity.this);
							AlertUtils.dismiss();
							break;
						default:
							break;
						}
					}
				});
	}

	/**
	 * 上传头像
	 */
	private void submitphoto() {
		VolleyBasic.getInstance(PersonalActivity.this).post(Cache.headinfo,
				VolleyMap.getInstance().headInfo(Bitmap64), NormalItem.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						NormalItem normalItem = (NormalItem) vd.getData();
						// 设置图片
						photoImg.setImageBitmap(clipBitmap);
						String imgUrl = normalItem.data;
						AppUtil.getUser().setAvatarurl(imgUrl);
						try {
							// 保存头像
							String path = null;
							if (!StringUtils.isEmpty(imgUrl)) {
								String name = MD5.getMD5(imgUrl)
										+ imgUrl.substring(imgUrl
												.lastIndexOf("."));
								// 保存头像地址
								path = Environment
										.getExternalStorageDirectory()
										+ "/YJB/" + name;
							}
							BitmapUtil.saveBitmapToFile(clipBitmap, path);
							// 保存头像地址
							MySharedPreferences
									.getMySharedPreferences(mContext).setValue(
											"HeadURL", path);
							MainActivity.isRefreshPersonal = true;
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						showToast("上传头像失败");
					}
				});

	}

	/**
	 * 下载并保存图片
	 */
	private void downloadAndSaveHeadImage() {
		if (!StringUtils.isEmpty(AppUtil.getUser().getAvatarurl())) {
			ImageListener listener = ImageLoader.getImageListener(photoImg,
					android.R.drawable.ic_menu_rotate,
					android.R.drawable.ic_delete);
			mImageLoader.get(AppUtil.getUser().getAvatarurl(),
					new ImageListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onResponse(ImageContainer response,
								boolean isImmediate) {
							// TODO Auto-generated method stub
							try {
								Bitmap head = response.getBitmap();
								if (head != null) {
									String imgUrl = AppUtil.getUser().getPath();
									// 保存头像
									String path = null;
									if (!StringUtils.isEmpty(imgUrl)) {
										String name = MD5.getMD5(imgUrl)
												+ imgUrl.substring(imgUrl
														.lastIndexOf("."));
										// 保存头像地址
										path = Environment
												.getExternalStorageDirectory()
												+ "/YJB/" + name;
										BitmapUtil.saveBitmapToFile(head, path);
										MySharedPreferences
												.getMySharedPreferences(
														mContext).setValue(
														"HeadURL", path);
									}
									photoImg.setImageBitmap(BitmapUtil
											.toRoundCorner(head, 8));
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (!StringUtils.isEmpty(PhotoPath)) {
								BitmapUtil.deleteBitmap(PhotoPath);
							}
						}
					});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			if (uri != null) {
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",
						BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			} else {
				// 防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@SuppressWarnings("unused")
					@Override
					public void run() {
						if (uri != null) {
							Intent i = new Intent(mContext, Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil
									.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			// 判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",
						BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if (requestCode == 200) {
			if (data != null) {
				// 获取剪切后的图片路径
				PhotoPath = data.getExtras().getString("PhotoPath");
				if (!StringUtils.isEmpty(PhotoPath)) {
					Log.d("log", PhotoPath);
					clipBitmap = BitmapUtil.getSmallFilletBitmap(PhotoPath,
							500, 500);
					Bitmap64 = BitmapUtil.bitmaptoString(clipBitmap);
					submitphoto();
				}
			}
		}
	}

	// 对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getBooleanExtra("UmengPush", false) == true) {
				// 友盟是否有消息(系统/收款/订单签收/消息)
				if ("0".equals(intent.getStringExtra("PushType"))
						|| "2".equals(intent.getStringExtra("PushType"))
						|| "4".equals(intent.getStringExtra("PushType"))
						|| "9".equals(intent.getStringExtra("PushType"))) {
					MainActivity.isSystemPush = "1";
				}
				unreadMessage_icon.setVisibility(View.VISIBLE);
			}
			if (intent.getBooleanExtra("HXPush", false) == true) {
				unreadMessage_icon.setVisibility(View.VISIBLE);
			}
			if (intent.getBooleanExtra("isCloseActivity", false) == true) {
				finish();
			}
		}
	};


	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
